package com.springboot.jeesite.modules.sys.service;

import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.NumberUtil;
import com.springboot.jeesite.common.utils.DateUtils;
import com.springboot.jeesite.modules.sys.entity.OsInfo;
import com.springboot.jeesite.modules.sys.entity.OsSysFile;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.lang.management.ManagementFactory;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 服务器相关信息
 */
public class OsInfoService {
    private static final int OSHI_WAIT_SECOND = 1000;

    private OsInfo osInfo;

    public OsInfo copyTo() throws Exception {
        osInfo = new OsInfo();
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        setCpuInfo(hal.getProcessor());
        setMemInfo(hal.getMemory());
        setSysInfo();
        setJvmInfo();
        setSysFiles(si.getOperatingSystem());
        return osInfo;
    }

    /**
     * 设置CPU信息
     *
     * @param processor
     */
    private void setCpuInfo(CentralProcessor processor) {
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        osInfo.setCpuNum(processor.getLogicalProcessorCount());
        osInfo.setCpuTotal(totalCpu);
        osInfo.setCpuSysUsed(cSys);
        osInfo.setCpuUserUsed(user);
        osInfo.setCpuWait(iowait);
        osInfo.setCpuFree(idle);
    }

    /**
     * 设置内存信息
     *
     * @param memory
     */
    private void setMemInfo(GlobalMemory memory) {
        osInfo.setMemTotal(convertFileSize(memory.getTotal()));
        osInfo.setMemUsed(convertFileSize(memory.getTotal() - memory.getAvailable()));
        osInfo.setMemFree(convertFileSize(memory.getAvailable()));
        osInfo.setMemUsage(NumberUtil.mul(NumberUtil.div(memory.getTotal() - memory.getAvailable(), memory.getTotal(), 4), 100));
    }

    /**
     * 设置服务器信息
     */
    private void setSysInfo() {
        Properties props = System.getProperties();
        osInfo.setSysComputerName(NetUtil.getLocalhost().getHostName());
        osInfo.setSysComputerIp(NetUtil.getLocalhost().getHostAddress());
        osInfo.setSysOsName(props.getProperty("os.name"));
        osInfo.setSysOsArch(props.getProperty("os.arch"));
        osInfo.setSysUserDir(props.getProperty("user.dir"));
    }

    /**
     * 设置Java虚拟机
     *
     * @throws UnknownHostException
     */
    private void setJvmInfo() throws UnknownHostException {
        Properties props = System.getProperties();
        osInfo.setJvmTotal(convertFileSize(Runtime.getRuntime().totalMemory()));
        osInfo.setJvmMax(convertFileSize(Runtime.getRuntime().maxMemory()));
        osInfo.setJvmFree(convertFileSize(Runtime.getRuntime().freeMemory()));
        osInfo.setJdkVersion(props.getProperty("java.version"));
        osInfo.setJdkHome(props.getProperty("java.home"));
        osInfo.setJvmStartTime(DateUtils.formatDateTime(DateUtils.getServerStartDate()));
        osInfo.setJvmRunTime(DateUtils.getDatePoor(new Date(), DateUtils.getServerStartDate()));
        osInfo.setJvmName(ManagementFactory.getRuntimeMXBean().getVmName());
        osInfo.setJvmUsed(convertFileSize(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        osInfo.setJvmUsage(NumberUtil.mul(NumberUtil.div(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), Runtime.getRuntime().totalMemory(), 4), 100));
    }


    /**
     * 设置磁盘信息
     */
    private void setSysFiles(OperatingSystem os) {
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        List<OsSysFile> sysFiles = new ArrayList<OsSysFile>();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            OsSysFile sysFile = new OsSysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            sysFile.setUsage(NumberUtil.mul(NumberUtil.div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }
        osInfo.setSysFiles(sysFiles);
    }

    /*
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */

    public String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }
}
